package cn.sinokj.party.chineseFourParty.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.base.BaseActivity;
import cn.sinokj.party.chineseFourParty.bean.StartImgPath;
import cn.sinokj.party.chineseFourParty.bean.Version;
import cn.sinokj.party.chineseFourParty.service.HttpConstants;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.Utils;
import cn.sinokj.party.chineseFourParty.utils.update.UpdateManager;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import pub.devrel.easypermissions.EasyPermissions;

public class FiringActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private static final int UPDATE = 101;
    private static final int STARTIMAGENAME = 102;
    @BindView(R.id.iv_bg)
    ImageView iv_bg;
    private Version version;
    private UpdateManager updateManager;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                Intent intent = new Intent(FiringActivity.this, LoginInActivity.class);
                intent.putExtra("isTourists", true);
                startActivity(intent);
                finish();
            }
            return false;
        }
    });
    private DialogInterface.OnDismissListener onDismissListener = new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            if (!updateManager.isUpdateOperator()) {
                handler.sendEmptyMessageDelayed(0, 2000);
            }
        }
    };
    private String updateMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.firing);
        ButterKnife.bind(this);
        new Thread(new LoadDataThread(STARTIMAGENAME)).start();
        /*String startImgURL = preferencesUtil.getString("startImgURL");
        if(TextUtils.isEmpty(startImgURL)){
            iv_bg.setImageResource(R.drawable.start2);
        }else {
            Glide.with(this).load(startImgURL).into(iv_bg);
        }*/
        EventBus.getDefault().register(this);
        new Thread(runnable).start();
    }

    String url = "http://192.168.1.232:8080/cloudPartyApp/images/time.jpg";

    private boolean connectFaild = true;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 4秒后直接跳转
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                logger.e(e);
            }
            if (connectFaild) {
                handler.sendEmptyMessageDelayed(0, 500);
            }
        }
    };

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case UPDATE:
                return HttpDataService.update();

            case STARTIMAGENAME:
                return HttpDataService.startphoto();
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        switch (msg.what) {
            case UPDATE:
                connectFaild = false;
                version = new Gson().fromJson(jsonObject.toString(), Version.class);
                DialogShow.closeDialog();
                int appVersionCode = Utils.getAppVersionCode(this);
                if (version.vcVersionCode > appVersionCode) {
                    updateManager = new UpdateManager(this, version.vcUrl);
                    if (version.tContent != null && !version.tContent.isEmpty()) {
                        updateMessage = version.tContent;
                    } else {
                        updateMessage = "您确定执行操作吗？";
                    }
                    updateConfirmAction(updateMessage, "确定", "取消", new ConfirmInterface() {
                        @Override
                        public void onOkButton() {
                            //更新
                            updateManager.showDownloadDialog();
                        }

                        @Override
                        public void onCancelButton() {
                        }

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (!updateManager.isUpdateOperator()) {
                                handler.sendEmptyMessageDelayed(0, 2000);
                            }
                        }
                    });

                } else {
                    handler.sendEmptyMessageDelayed(0, 2000);
                }
                break;
            case STARTIMAGENAME:
                new Thread(new LoadDataThread(UPDATE)).start();
                //  String vcIcon = jsonObject.optString("vcIcon");
                String json = jsonObject.toString();
                StartImgPath startImgPath = new Gson().fromJson(json, StartImgPath.class);
                /*String startImgURL = preferencesUtil.getString("startImgURL");
                if(!TextUtils.equals(vcIcon,startImgURL)){
                    preferencesUtil.putString("startImgURL",vcIcon);
                }*/
                Glide.with(this).load(startImgPath.vcIcon).into(iv_bg);
                break;
        }

    }

    public void toMainActivity() {
        handler.sendEmptyMessageDelayed(0, 2000);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        updateManager.installApk();
        System.out.println("");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg) {
        if (msg.what == UpdateManager.DOWN_OVER) {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(this, perms)) {
                updateManager.installApk();
            } else {
                EasyPermissions.requestPermissions(this, "请求访问SD卡", HttpConstants.EXTERNAL_STORAGE, perms);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
    }
}
